package cn.usian.service.impl;

import cn.usian.dto.SetmealDto;
import cn.usian.pojo.Category;
import cn.usian.pojo.Setmeal;
import cn.usian.service.CategoryService;
import cn.usian.service.SetmealDishService;
import cn.usian.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;



    @Override
    public Page<SetmealDto> findPage(Integer page, Integer pageSize, String name) {

        //查询条件
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        if (name != null && name != "") {
            //去掉前后空格
            name = name.trim();
            wrapper.like(Setmeal::getName, name);
        }
        //展示没有删除的条件
        wrapper.eq(Setmeal::getIsDeleted, 0);
        //添加排序条件，根据更新时间降序排列
        wrapper.orderByDesc(Setmeal::getUpdateTime);
        Page<Setmeal> page1 = this.page(pageInfo, wrapper);
        //判断
        if (page1 == null) {
            return null;
        }
        //再次封装属性,获得所有的套餐信息
        List<Setmeal> records = page1.getRecords();
        List<SetmealDto> setmealDtos = new ArrayList<>();
        //遍历所有套餐对象那个,转成一个dto
        records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            //查询分类的名字
            Category byId = categoryService.getById(setmealDto.getCategoryId());
            setmealDto.setCategoryName(byId.getName());
            setmealDtos.add(setmealDto);
            return item;
        }).collect(Collectors.toList());

        Page<SetmealDto> dtoPage = new Page<>();
        dtoPage.setRecords(setmealDtos);
        dtoPage.setTotal(page1.getTotal());
        return dtoPage;
    }

}
